package org.xx.armory.swing.components;

import org.xx.armory.swing.DialogUtils;
import org.xx.armory.swing.builders.UIModelClass;

import javax.swing.*;

import static org.xx.armory.commons.Validators.notBlank;

/**
 * 确认输入对话框。
 */
@UIModelClass
public class ConfirmInputDialog
        extends DialogPane {
    private static final int DEFAULT_VALUE_COLUMNS = 20;
    private final String expectedValue;

    public ConfirmInputDialog(
            String expectedValue
    ) {
        expectedValue = notBlank(expectedValue, "expectedValue").trim();

        final JTextField valuePane = controller().get(JTextField.class, "value");
        valuePane.setColumns(getValueColumns());
        final int preferredWidth = valuePane.getPreferredSize().width;

        final String message = controller().formatMessage("prompt", expectedValue);
        controller().setText("prompt",
                             "<html><body style=\"margin:0;padding:0;width:" + preferredWidth + "px;\" >" + message + "</body></html>");

        this.expectedValue = expectedValue;

    }

    protected int getValueColumns() {
        return DEFAULT_VALUE_COLUMNS;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void done(
            int result
    ) {
        if (result == DialogPane.OK) {
            final String value = controller().getText("value").trim();
            if (value.equals(this.expectedValue)) {
                super.done(result);
            } else {
                DialogUtils.warn(this.getOwner(), controller().getMessage("value-warn"));

                controller().setText("value", null);
                controller().get(JTextField.class, "value").requestFocusInWindow();
            }
        } else {
            super.done(result);
        }
    }
}
